package com.example.demo.work.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class ExportCsvUtils {

    private static Logger log = LoggerFactory.getLogger(ExportCsvUtils.class);

    public static void exportCsv(String filePath, String strValue, String header, Boolean headFlag) {
        try {
            File file = new File(filePath);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file, true), "GBK");
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
            if (headFlag) {
                bufferedWriter.write(header);
            }
            if (StringUtils.isNotBlank(strValue)) {
                bufferedWriter.write(strValue.toString());
            }
            bufferedWriter.flush();
            outputStreamWriter.close();
            bufferedWriter.close();
        } catch (Exception e) {
            log.warn("写文件异常", e);
        }
    }

    public static void readLocalExport(String filePath, String fileName, OutputStream outputStream) {
        InputStream in = null;
        try {
            in = new FileInputStream(filePath + fileName);
            int len = 0;
            //5.创建数据缓冲区
            byte[] buffer = new byte[1024];
            //7.将FileInputStream流写入到buffer缓冲区
            while ((len = in.read(buffer)) > 0) {
                //8.使用OutputStream将缓冲区的数据输出到客户端浏览器
                outputStream.write(buffer, 0, len);
            }
        } catch (Exception e) {
            log.warn("导出文件发生异常", e);
        } finally {
            try {
                in.close();
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                log.warn("关闭流出现异常", e);
            }
        }

    }
}
